package com.bac.rentmap.manager.impl;

import com.bac.rentmap.manager.StreetManager;
import com.bac.rentmap.model.Street;
import com.bac.rentmap.jdo.JdoSupport;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import java.util.List;

/**
 *
 * @author Ivan Holub
 */
public class StreetManagerImpl extends JdoSupport implements StreetManager {
    public List<Street> getStreets(int number) {
        PersistenceManager pm = getPersistenceManager();
        Query query = pm.newQuery(Street.class);
        query.setRange(0, number);
        List<Street> list = (List<Street>) query.execute();
        list.size();
        pm.close();
        return list;
    }

    public void saveStreets(List<Street> list) {
        PersistenceManager pm = getPersistenceManager();
        int maxNumber = getMaxNumberImpl(pm);
        int i = maxNumber;
        for (Street b : list) {
            i++;
            b.setNumber(i);
            pm.makePersistent(b);
        }
        pm.close();
    }

    public void clearStreets(int number) {
        PersistenceManager pm = getPersistenceManager();
        Query query = pm.newQuery(Street.class);
        query.setOrdering("number desc");
        query.setRange(0, number);
        List<Street> list = (List<Street>) query.execute();
        list.size();
        for (Street b : list) {
            pm.deletePersistent(b);
        }
        pm.close();
    }

    public int getMaxNumber() {
        PersistenceManager persistenceManager = getPersistenceManager();
        try {
            return getMaxNumberImpl(persistenceManager);
        } finally {
            persistenceManager.close();
        }
    }

    private int getMaxNumberImpl(PersistenceManager persistenceManager) {
        Query query = persistenceManager.newQuery(Street.class);
        query.setOrdering("number desc");
        query.setRange(0, 1);
        List<Street> list = (List<Street>) query.execute();
        int retValue = 0;
        if (list.size() > 0) {
            Street b = list.get(0);
            if (b.getNumber() == null) {
                retValue = -1;
            } else {
                retValue = Integer.valueOf(b.getNumber());
            }
        }
        return retValue;
    }
    
}
